package com.example.vertification.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;

import java.util.Map;
import java.util.UUID;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;

@RestController
@Api(value = "文字转音频", tags = "文字转音频")
public class TextVoiceController {


    @GetMapping("/text_to_voice")
    @ApiOperation(value = "传入类型为字符串text,获取一段音频")
    public ResponseEntity<Resource> text_to_voice(@RequestParam String text) {
        String URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={appid}&client_secret={key}";
        String appid = "语音合成appid";
        String key = "语音合成key";
        String Access_token =  new JSONObject(HttpUtil.get(URL.replace("{key}",key).replace("{appid}",appid))).getStr("access_token");
        String Send_To_Url = "http://tsn.baidu.com/text2audio?tex="+text+"&lan=zh&cuid="+ UUID.randomUUID()+"&ctp=1&tok={token}&per=1".replace("{token}",Access_token);

        byte[] audioData = HttpRequest.post(Send_To_Url)
                .header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") // 根据百度API的要求设置Content-Type
                .execute()
                .bodyBytes();
        Resource resource = new ByteArrayResource(audioData);
        System.out.println(Send_To_Url);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentLength(audioData.length);
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

}
